import { exec } from 'child_process'
import * as fs from 'fs'
import * as querystring from 'querystring'
import { article, articlesTitle } from '../mongoose'
import { uuid } from '../utils/index'

export function staticFile(response, resource) {
	const suffix = resource.split('.').pop()
	let type
	if (suffix === 'jpg' || suffix === 'jpeg') {
		type = 'jpeg'
	} else if (suffix === 'png') {
		type = 'png'
	} else {
		response.writeHead(500, { 'Content-Type': 'text/plain' })
		response.write('只允许格式为jpg/jpeg/png的图片')
		response.end()
		return
	}
	fs.readFile(`./static/${resource}`, 'binary', (error, file) => {
		if (error) {
			response.writeHead(500, { 'Content-Type': 'text/plain' })
			response.write(error + '\n')
			response.end()
		} else {
			response.writeHead(200, { 'Content-Type': `image/${type}` })
			response.write(file, 'binary')
			response.end()
		}
	})
}

export function getArticlesTitle(request, response) {
	const nid = request.url.split('?').pop()
	const query = querystring.parse(nid)
	response.writeHead(200, { 'Content-Type': 'text/plain' })
	articlesTitle.find(query).then((doc) => {
		console.log('doc', doc)
		const obj = {
			code: 200,
			data: {
				articles: doc,
			},
		}
		const contents = JSON.stringify(obj)
		response.write(contents)
		response.end()
	})
}

export function setArticle(request, response) {
	let post = ''
	request.on('data', function (chunk) {
		post += chunk
	})
	request.on('end', function () {
		const postObj = querystring.parse(post)
		article.find({ aid: postObj.aid }).then((doc) => {
			//新建文章
			if (doc.length === 0) {
				article
					.find({ notebookName: postObj.notebookName })
					.then((document) => {
						if (document[0]) {
							;(postObj.nid as unknown) = document[0].nid
						} else {
							;(postObj.nid as unknown) = uuid()
						}
						// console.log('postObj', postObj)
						new article(postObj).save()
						console.log('create')

						delete postObj.content
						// console.log('titlePostObj', postObj)
						new articlesTitle(postObj).save()
					})
			} else {
				//修改文章
				article.find({ notebookName: postObj.notebookName }).then((doc) => {
					if (!doc[0]) {
						;(postObj.nid as unknown) = uuid()
						article.updateOne({ aid: postObj.aid }, postObj).then()
					} else {
						article.updateOne({ aid: postObj.aid }, postObj).then()
					}
					delete postObj.content
					articlesTitle.updateOne({ aid: postObj.aid }, postObj).then()
				})
			}
		})

		response.writeHead(200, { 'Content-Type': 'text/plain' })
		// const contents = JSON.stringify(postObj)
		const content = {
			code: 200,
			data: {
				message: 'success',
			},
		}
		response.write(JSON.stringify(content))
		response.end()
	})
}

export function getNotebookList(request, response) {
	articlesTitle.find().then((doc) => {
		console.log(doc)
		let notebookList: any = []
		let map = {}
		for (let item of doc) {
			map[item['nid']] = item['notebookName']
		}
		for (let key in map) {
			notebookList.push({ nid: key, notebookName: map[key] })
		}
		response.writeHead(200, { 'Content-Type': 'text/plain' })
		const obj = {
			code: 200,
			data: {
				notebookList: notebookList,
			},
		}
		const contents = JSON.stringify(obj)
		response.write(contents)
		response.end()
	})
}

export function getArticle(request, response) {
	const str = request.url.split('?').pop()
	const query = querystring.parse(str)

	article.find(query).then((doc) => {
		response.writeHead(200, { 'Content-Type': 'text/plain' })
		const obj = {
			code: 200,
			data: {
				article: doc[0],
			},
		}
		const contents = JSON.stringify(obj)
		response.write(contents)
		response.end()
	})
}

export function deleteArticle(request, response) {
	const str = request.url.split('?').pop()
	const query = querystring.parse(str)

	article.deleteOne(query).then()
	articlesTitle.deleteOne(query).then()

	response.writeHead(200, { 'Content-Type': 'text/plain' })
	const obj = {
		code: 200,
		data: {
			message: 'success',
		},
	}
	const contents = JSON.stringify(obj)
	response.write(contents)
	response.end()
}
